"""__author__ = 贺仕豪"""
import pymysql


def db_conn():
    """连接数据库"""
    conn = pymysql.connect(
        host='47.100.204.110',
        user='root',
        passwd='123456',
        port=3306,
        database='chat',
        charset='utf8'
    )
    return conn


class OperateError(Exception):
    """自定义异常类型"""
    print('操作失败！')


def db_insert(sql, *args):
    """数据库插入操作"""
    con = db_conn()
    try:
        with con.cursor() as cursor:
            results = cursor.execute(sql, *args)
            if results > 0:
                print('操作成功！')
        con.commit()
    except OperateError:
        con.rollback()
    finally:
        con.close()


def db_delete():
    pass


def db_update(sql, *args):
    """数据库更新操作"""
    con = db_conn()
    try:
        with con.cursor() as cursor:
            results = cursor.execute(sql, *args)
            if results > 0:
                print('操作成功！')
        con.commit()
    except OperateError:
        con.rollback()
    finally:
        con.close()


def db_select(sql, *args):
    """数据库查找操作"""
    con = db_conn()
    try:
        with con.cursor() as cursor:
            results = cursor.execute(sql, *args)
            if results > 0:
                query = cursor.fetchall()
                return query
            return False
    finally:
        con.close()

